import Vue from 'vue'
import axios from 'axios'
import { VueAxios } from './axios'
import store from '@/store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Message, MessageBox, Loading } from 'element-ui'

//内存中正在请求的数量
let loadingNum = 0
let loading = null //定义loading变量
function startLoading() {
  if (loadingNum == 0) {
    loading = Loading.service({
      lock: true,
      text: '努力加载中...',
      background: 'rgba(0, 0, 0, 0.5)',
    })
  }
  // 请求数量加1
  loadingNum++
}
function endLoading() {
  // 请求数量减1
  loadingNum--
  if (loadingNum <= 0) {
    loading.close()
  }
}

/**
 * 【指定 axios的 baseURL】
 * @type {*|string}
 */
let apiBaseUrl = process.env.VUE_APP_BASE_URL || '/api'

// 创建 axios 实例
const service = axios.create({
  baseURL: apiBaseUrl,
  timeout: 60000, // 请求超时时间
})

const handleError = (error) => {
  endLoading()
  if (error.response) {
    let data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    switch (error.response.status) {
      case 403:
        Message.error('拒绝访问')
        break
      case 500:
        if (token && data.message == 'Token失效，请重新登录') {
          MessageBox.alert('很抱歉，登录已过期，请重新登录', '登录已过期', {
            type: 'danger',
            center: true,
            confirmButtonText: '重新登录',
            callback: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                window.location.reload()
              })
            },
          })
        }
        break
    }
  }
  return Promise.reject(error)
}

// request 请求拦截器
service.interceptors.request.use(
  (config) => {
    startLoading()
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (token) {
      config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    if (config.method == 'get') {
      if (config.url.indexOf('/sys/dict/getDictItems') < 0) {
        config.params = {
          _t: Date.parse(new Date()) / 1000,
          ...config.params,
        }
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response 响应拦截器
service.interceptors.response.use((response) => {
  endLoading()
  if (response.data.success !== true && response.data.code !== 1) {
    let message = response.data.message || '网络异常，请稍后再试'
    Message.error(message)
    throw new Error(message)
  } else {
    return response.data
  }
}, handleError)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  },
}

export { installer as VueAxios, service as axios }
